package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Util {

    public static WebDriver driver;

    public static void createDriver(){
        if(driver==null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions option=new ChromeOptions();
            //强制运行所有的链接
            option.addArguments("--remote-allow-origins=*");
            
            driver=new ChromeDriver(option);
            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
    }
    public Util(String url){
        createDriver();
        driver.get(url);
    }

    public void getScreenShot(String name) throws IOException {

        SimpleDateFormat sim1=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2=new SimpleDateFormat("HHmmssSS");

        String dirTime=sim1.format(System.currentTimeMillis());
        String fileTime=sim2.format(System.currentTimeMillis());


        String fileName=new String("./src/test/image/"+dirTime+"/"+name+"-"+fileTime+".png");

        File file=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(file,new File(fileName));
    }
}
